package n12_线程活跃性和锁粒度细分;

import lombok.extern.slf4j.Slf4j;
import utils.Sleeper;

/**
 * @author fu
 * @date 2021-12-29 14:36
 * 概要：
 *     BigRoom                   一把大锁
 *     BigRoom_StudyRoom_BedRoom 细密度的多把锁，提高并发性 【前提 业务不能有关联】
 *
 * 锁粒度细分：
 *  1. 好处， 增强并发度
 *  2. 坏处， 如果一个线程同时获得多把锁，容易发生死锁
 */
@Slf4j(topic = "c.T1")
public class T1_more_locak {

    public static void main(String[] args) {
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

//        final BigRoom bigRoom = new BigRoom();
//========================================
        final BigRoom_StudyRoom_BedRoom bigRoom = new BigRoom_StudyRoom_BedRoom();
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        new Thread(()->{
            bigRoom.study();
        },"小南").start();

        new Thread(()->{
            bigRoom.sleep();
        },"大女").start();


        log.debug("结束。。。。。。。。");

    }
}

@Slf4j(topic = "c.Big")
class BigRoom{

    public void sleep(){
        synchronized (this){
            log.debug("sleep 2 h");
            Sleeper.sleep(2);
        }
    }

    public void study(){
        synchronized (this){
            log.debug("sleep 1 h");
            Sleeper.sleep(1);
        }
    }
}

@Slf4j(topic = "c.Big")
class BigRoom_StudyRoom_BedRoom{
    private final Object studyRoom = new Object();
    private final Object bedRoom = new Object();

    public void sleep(){
        synchronized (bedRoom){
            log.debug("sleep 2 h");
            Sleeper.sleep(2);
        }
    }

    public void study(){
        synchronized (studyRoom){
            log.debug("study 1 h");
            Sleeper.sleep(1);
        }
    }

}

